package com.ferry.wallpaper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ferry.wallpaper.mapper.UserMapper;
import com.ferry.wallpaper.mapper.UserWallMapper;
import com.ferry.wallpaper.domain.User;
import com.ferry.wallpaper.domain.UserWall;
import com.ferry.wallpaper.service.UserService;
import com.ferry.wallpaper.utils.EmailUtils;
import com.ferry.wallpaper.utils.Response;
import com.ferry.wallpaper.utils.ResponseGenerator;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserWallMapper userWallMapper;

    @Autowired
    private ResponseGenerator generator;

    @Autowired
    private MinioClient client;

    private static final String MINIO_BUCKET = "app";

    @Override
    public Response register(String email, String password) {
        if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
            if (EmailUtils.isValidEmail(email)) {
                User user = new User();
                user.setUserAvatar(null);
                user.setUserEmail(email);
                user.setUserPassword(password);
                user.setUserProfile("TA很懒，什么都没有留下......");
                user.setUserNickname("摆渡人");
                user.setUserMoney(100);
                user.setUserSex(1);
                user.setUserLevel(0);
                user.setUserBirth(new Date());
                int insert = userMapper.insert(user);
                User vp = userMapper.selectOne(new QueryWrapper<User>().eq("USER_EMAIL", email));
                if (insert > 0) {
                    return generator.success("注册成功", vp);
                } else {
                    return generator.fail("注册失败");
                }
            } else {
                return generator.fail("邮箱非法");
            }
        } else {
            return generator.fail("邮箱或密码不能为空");
        }
    }

    @Override
    public Response login(String email, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("USER_EMAIL", email);
        User user = userMapper.selectOne(wrapper);
        if (user != null) {
            if (user.getUserPassword().equals(password)) {
                return generator.success("注册成功", user);
            } else {
                return generator.fail("密码错误");
            }
        } else {
            return generator.fail("用户不存在");
        }
    }

    @Override
    public User get(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean sign(Long id) {
        User user = userMapper.selectById(id);
        user.setUserLevel(user.getUserLevel() + 1);
        int i = userMapper.updateById(user);
        return i > 0;
    }

    @Override
    public boolean buy(Long wallId, Long userId, Integer price) {

        QueryWrapper<UserWall> wrapper = new QueryWrapper<UserWall>().
                eq("USER_ID", userId).
                eq("WALL_ID", wallId);
        UserWall userWall1 = userWallMapper.selectOne(wrapper);

        if (userWall1 == null) {
            User user = userMapper.selectById(userId);
            user.setUserMoney(user.getUserMoney() - price);
            int i = userMapper.updateById(user);
            UserWall userWall = new UserWall();
            userWall.setUserId(userId);
            userWall.setWallId(wallId);
            userWall.setTime(new Date());
            int insert = userWallMapper.insert(userWall);
            return i > 0 && insert > 0;
        } else {
            return true;
        }
    }

    @Override
    public boolean update(User user) {
        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean modifyIcon(Long id, byte[] bytes, String name) {
        try {
            client.putObject(PutObjectArgs.builder().bucket(MINIO_BUCKET).object("user_" + id+ name).build());
        } catch (Exception e) {
            return false;
        }
        User user = userMapper.selectById(id);
        try {
            user.setUserAvatar(client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.
                    builder().method(Method.GET).bucket(MINIO_BUCKET).object("user_" + id+ name).build()));
        } catch (Exception e) {
           return false;
        }
        int i = userMapper.updateById(user);
        return i > 0;
    }
}
